package com.booksystem.campuslibrarymanagementsystem.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class EmailSender {

    private EmailSender(){}

    final static String USERNAME = "2951965544@qq.com";
    final static String PASSWORD = "suslvjcxznvtdeic";

    private static void email(String toEmail,String mage) {
        // 发件人邮箱、密码（这里的密码不是邮箱登录密码，而是开启SMTP服务后获得的授权码）


        // 收件人邮箱
        String to = toEmail;

        // 邮件服务器配置
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com"); // SMTP服务器地址
        props.put("mail.smtp.port", "465"); // QQ邮箱SMTP端口
        props.put("mail.smtp.auth", "true"); // 需要验证
        props.put("mail.smtp.ssl.enable", "true"); // 启用SSL
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.socketFactory.port", "465");

        // 创建会话
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(USERNAME, PASSWORD);
                    }
                });

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            try {
                message.setFrom(new InternetAddress(USERNAME)); // 设置发件人
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // 设置收件人
                message.setSubject("校园图书管理系统通知"); // 设置邮件标题
                message.setText(mage); // 设置邮件正文

            } catch (MessagingException e) {
                e.printStackTrace();
            }
            // 发送邮件
            Transport.send(message);

            System.out.println("邮件已成功发送！");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void sendEmails(String toEmail,String mage){
        email(toEmail,mage);
    }

}